const CostStatisticsModel = require("../model/CostStatisticsModel");

class CostStatisticsController {
  constructor() {
    this.model = new CostStatisticsModel();
  }

  _getCommonFilters(req) {
    // 获取筛选
    const { startDate, endDate, stallIds, statusList, purposeList } = req.query;

    const getArrayParam = (param) => {
      if (typeof param === "string") {
        return param.split(",").filter((id) => id);
      }
      if (Array.isArray(param)) {
        return param;
      }
      return null;
    };

    return {
      startDate,
      endDate,
      stallIds: getArrayParam(stallIds),
      statusList: getArrayParam(statusList),
      purposeList: getArrayParam(purposeList),
    };
  }

  // 获取就餐人数
  // GET /costStatistics/diningCount?startDate=YYYY-MM-DD&endDate=YYYY-MM-DD

  async getDiningCount(req, res) {
    try {
      const { startDate, endDate } = req.query;
      const result = await this.model.getDiningCountByDateRange(
        startDate,
        endDate
      );

      return res.json({
        code: 0,
        msg: "就餐人数（范围）查询成功",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，查询就餐人数失败。",
      });
    }
  }

  // 按分类统计出库数量
  // GET /costStatistics/categoryOutboundQuantityStat?stallIds=1,2&startDate=...

  async getCategoryOutboundQuantityStat(req, res) {
    try {
      const filters = this._getCommonFilters(req);
      const result = await this.model.getCategoryOutboundQuantityStat(
        filters.statusList,
        filters.startDate,
        filters.endDate,
        filters.purposeList,
        filters.stallIds
      );

      return res.json({
        code: 0,
        msg: "按分类出库数量统计成功",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，按分类出库数量统计失败。",
      });
    }
  }

  // 按分类和档口统计出库总金额
  // GET /costStatistics/purchaseCostAnalysis?stallIds=1,2&startDate=...

  async getPurchaseCostAnalysis(req, res) {
    try {
      const filters = this._getCommonFilters(req);
      const result = await this.model.getPurchaseCostAnalysis(
        filters.statusList,
        filters.startDate,
        filters.endDate,
        filters.purposeList,
        filters.stallIds
      );

      return res.json({
        code: 0,
        msg: "出库成本分析成功",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，出库成本分析失败。",
      });
    }
  }

  // 按档口统计总金额
  // GET /costStatistics/stallCostRatioStat?stallIds=1,2&startDate=...

  async getStallCostRatioStat(req, res) {
    try {
      const filters = this._getCommonFilters(req);
      const result = await this.model.getStallCostRatioStat(
        filters.statusList,
        filters.startDate,
        filters.endDate,
        filters.purposeList,
        filters.stallIds
      );

      return res.json({
        code: 0,
        msg: "按档口成本占比统计成功",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，按档口成本占比统计失败。",
      });
    }
  }

  // 按分类统计食材种类数量
  // GET /costStatistics/goodsCountByCategoryStat

  async getGoodsCountByCategoryStat(req, res) {
    try {
      const result = await this.model.getGoodsCountByCategoryStat();

      return res.json({
        code: 0,
        msg: "按分类统计食材种类数量成功",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，按分类统计食材种类数量失败。",
      });
    }
  }

  // 每日总成本、档口成本趋势统计
  // GET /costStatistics/dailyTotalCostStat?stallIds=1,2&startDate=...
  async getDailyTotalCostStat(req, res) {
    try {
      const filters = this._getCommonFilters(req);

      if (!filters.startDate || !filters.endDate) {
        return res.json({
          code: 1,
          msg: "缺少必需的日期参数 (startDate 和 endDate)。",
          data: null,
        });
      }

      const result = await this.model.getDailyTotalCostStat(
        filters.statusList,
        filters.startDate,
        filters.endDate,
        filters.purposeList,
        filters.stallIds
      );

      return res.json({
        code: 0,
        msg: "每日总成本趋势统计成功",
        data: {
          dates: result.dailyData.dates,
          series: result.dailyData.series,
        },
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，每日总成本趋势统计失败。",
        error: error.message,
      });
    }
  }
}

module.exports = CostStatisticsController;
